package com.travel.common.util;

import org.apache.commons.lang3.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import javax.net.ssl.HttpsURLConnection;
import javax.net.ssl.SSLContext;
import javax.net.ssl.SSLSocketFactory;
import javax.net.ssl.TrustManager;
import java.io.*;
import java.net.ConnectException;
import java.net.HttpURLConnection;
import java.net.URL;
import java.util.Map;
import java.util.Set;

/**
 * @author YiJiang
 * @date 2017/9/14
 * @desc https请求工具类
 */
public class HttpUtils {

    private static Logger logger = LoggerFactory.getLogger(HttpUtils.class);

    private static String CHARSET_UTF8 = "utf-8";

    public static String doPost(String url, String postData, int timeOut) throws  Exception{
        if (url.startsWith("https://")) {
            return httpsRequests(url, "POST", postData, timeOut, null);
        }else{
            return sendHttpPost(url, postData, timeOut, null);
        }
    }

    /**
     *
     * @param url
     * @param postData 请求数据
     * @param timeOut 超时时间
     * @param params 请求头数据
     * @return
     * @throws Exception
     */
    public static String doPost(String url, String postData, int timeOut, Map<String, String> params) throws  Exception{
        if (url.startsWith("https://")) {
            return httpsRequests(url, "POST", postData, timeOut, params);
        }else{
            return sendHttpPost(url, postData, timeOut, params);
        }
    }

    public static String doGet(String url, int timeOut) throws Exception{
        if (url.startsWith("https://")) {
            return httpsRequests(url, "GET", null, timeOut, null);
        }else{
            return sendHttpGet(url, timeOut, null);
        }
    }

    /**
     *
     * @param url
     * @param timeOut
     * @param params 请求头数据
     * @return
     * @throws Exception
     */
    public static String doGet(String url, int timeOut, Map<String, String> params) throws Exception{
        if (url.startsWith("https://")) {
            return sendHttpGet(url, timeOut, params);
        }else{
            return httpsRequests(url, "GET", null, timeOut, params);
        }
    }

    /**
     *
     * @param requestUrl 请求地址
     * @param requestMethod GET/POST
     * @param outputStr 请求数据
     * @param timeOut 超时时间
     * @return
     */
    public static String httpsRequests(String requestUrl, String requestMethod, String outputStr, int timeOut, Map<String, String> params) {
        InputStream inputStream = null;
        InputStreamReader inputStreamReader = null;
        BufferedReader bufferedReader = null;
        HttpsURLConnection conn = null;
        try {
            // 创建SSLContext对象，并使用我们指定的信任管理器初始化
            TrustManager[] tm = { new MyX509TrustManager() };
            SSLContext sslContext = SSLContext.getInstance("SSL", "SunJSSE");
            sslContext.init(null, tm, new java.security.SecureRandom());
            // 从上述SSLContext对象中得到SSLSocketFactory对象
            SSLSocketFactory ssf = sslContext.getSocketFactory();

            URL url = new URL(requestUrl);
            conn = (HttpsURLConnection) url.openConnection();
            conn.setSSLSocketFactory(ssf);

            conn.setDoOutput(true);
            conn.setDoInput(true);
            conn.setUseCaches(false);
            conn.setReadTimeout(timeOut);
            conn.setConnectTimeout(timeOut);
            // 设置请求方式（GET/POST）
            conn.setRequestMethod(requestMethod);
            if(params != null && params.size() > 0){
                Set<String> keys = params.keySet();
                for(String s : keys) {
                    conn.setRequestProperty(s, params.get(s));
                }
            }
//            conn.setRequestProperty("Content-Type", "application/json");

            // 当outputStr不为null时向输出流写数据
            if (null != outputStr) {
                OutputStream outputStream = conn.getOutputStream();
                // 注意编码格式
                outputStream.write(outputStr.getBytes(CHARSET_UTF8));
                outputStream.close();
            }

            // 从输入流读取返回内容
            inputStream = conn.getInputStream();
            inputStreamReader = new InputStreamReader(inputStream, CHARSET_UTF8);
            bufferedReader = new BufferedReader(inputStreamReader);
            String str = null;
            StringBuffer buffer = new StringBuffer();
            while ((str = bufferedReader.readLine()) != null) {
                buffer.append(str);
            }
            String btr = buffer.toString();

            return btr;
        } catch (ConnectException ce) {
            logger.error("连接超时：", ce);
        } catch (Exception e) {
            logger.error("https请求异常：", e);
        }finally {//释放资源
            if(bufferedReader != null){
                try {
                    bufferedReader.close();
                }catch (Exception e){
                    e.printStackTrace();;
                }
            }
            if(inputStreamReader != null){
                try {
                    inputStreamReader.close();
                }catch (Exception e){
                    e.printStackTrace();;
                }
            }
            if(inputStream != null){
                try {
                    inputStream.close();
                }catch (Exception e){
                    e.printStackTrace();;
                }
            }
            if(conn != null){
                try {
                    conn.disconnect();
                }catch (Exception e){
                    e.printStackTrace();;
                }
            }
        }
        return null;
    }

    /**
     * 发送GET请求
     *
     * @param urlString
     *            URL地址
     * @return 响应对象
     * @throws IOException
     */
    public static String sendHttpGet(String urlString, int timeOut, Map<String, String> params) throws IOException {
        return send(urlString, "GET", null, timeOut, params);
    }


    /**
     * 发送POST请求
     *
     * @param urlString
     *            URL地址
     * @return 响应对象
     * @throws IOException
     */
    public static String sendHttpPost(String urlString, String postData, int timeOut, Map<String, String> params) throws IOException {
        return send(urlString, "POST", postData, timeOut, params);
    }

    /**
     * 发送HTTP请求
     *
     * @param urlString
     * @return 响映对象
     * @throws IOException
     */
    private static String send(String urlString, String method, String postData, int timeOut, Map<String, String> params) throws IOException {
        HttpURLConnection urlConnection = null;

        if (method.equalsIgnoreCase("GET") && StringUtils.isNotBlank(postData)) {
            urlString = urlString + "?" +  postData;
        }
        URL url = new URL(urlString);
        urlConnection = (HttpURLConnection) url.openConnection();

        urlConnection.setRequestMethod(method);
        urlConnection.setDoOutput(true);
        urlConnection.setDoInput(true);
        urlConnection.setUseCaches(false);
        urlConnection.setConnectTimeout(timeOut);
        urlConnection.setReadTimeout(timeOut);
        if(params != null && params.size() > 0){
            Set<String> keys = params.keySet();
            for(String s : keys) {
                urlConnection.setRequestProperty(s, params.get(s));
            }
        }
//        urlConnection.setRequestProperty("Content-Type", "application/json");

        if (method.equalsIgnoreCase("POST") && StringUtils.isNotBlank(postData)) {

            urlConnection.getOutputStream().write(postData.getBytes());
            urlConnection.getOutputStream().flush();
            urlConnection.getOutputStream().close();
        }

        return makeContent(urlString, urlConnection);
    }


    /**
     * 得到响应对象
     *
     * @param urlConnection
     * @return 响应对象
     * @throws IOException
     */
    private static String makeContent(String urlString, HttpURLConnection urlConnection) throws IOException {
        StringBuilder builder=new StringBuilder();
        try {
            InputStream in = urlConnection.getInputStream();
            BufferedReader bufferedReader = new BufferedReader(
                    new InputStreamReader(in, CHARSET_UTF8));
            String line;
            while((line=bufferedReader.readLine())!=null){
                builder.append(line+"\n");
            }
            bufferedReader.close();

            return builder.toString();
        } catch (IOException e) {
            throw e;
        } finally {
            if (urlConnection != null) {
                urlConnection.disconnect();
            }
        }
    }
}
